<template>
  <div>
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :total="page.total"
        :viewFunc="handleView"
        :delFunc="handleDelete"
        :page-change="changePage"
        :editFunc="handleEdit"
      >
        <template #toolbarBtn>
          <el-button
            type="warning"
            :icon="CirclePlusFilled"
            @click="handleAdd"
            >新增</el-button
          >
          <el-button
            type="primary"
            :icon="UploadFilled"
            @click="handleImportClick"
            >导入</el-button
          >
          <el-button
            type="success"
            :icon="Download"
            @click="downloadTemplate"
            >下载模板</el-button
          >
        </template>
      </TableCustom>
    </div>
    <el-dialog
      :title="title"
      v-model="visible"
      width="800px"
      @close="closeDialog"
      destroy-on-close
    >
      <div class="content-dialog">
        <el-form ref="formRef" :disabled="title == '查看'" :model="trainerForm" :label-width="120">
          <el-divider content-position="left">基本信息</el-divider>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="姓名"
                prop="name"
                :rules="[
                  { required: true, message: '请输入', trigger: 'blur' },
                ]"
              >
                <el-input v-model="trainerForm.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="性别"
                prop="gender"
                :rules="[
                  { required: true, message: '请选择', trigger: 'change' },
                ]"
              >
                <el-select v-model="trainerForm.gender">
                  <el-option
                    v-for="item in genderList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="年龄"
                prop="age"
                :rules="[
                  {
                    required: true,
                    message: '请输入',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input-number
                  :min="0"
                  :max="100"
                  :step="1"
                  v-model="trainerForm.age"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="出生日期"
                prop="birthday"
                :rules="[
                  {
                    required: true,
                    message: '请选择',
                    trigger: 'change',
                  },
                ]"
              >
                <el-date-picker
                  v-model="trainerForm.birthday"
                  type="date"
                  placeholder="请选择"
                  style="width: 100%"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="家长"
                prop="contact"
                :rules="[
                  {
                    required: true,
                    message: '请输入',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input v-model="trainerForm.contact"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="联系电话"
                prop="tel"
                :rules="[
                  {
                    required: true,
                    message: '请输入',
                    trigger: 'blur',
                  },
                  {
                    trigger: 'blur',
                    message: '请输入正确电话号码',
                    validator: isPhoneNum,
                  },
                ]"
              >
                <el-input v-model="trainerForm.tel"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="家庭地址"
                prop="address"
                :rules="[
                  {
                    required: true,
                    message: '请输入',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input v-model="trainerForm.address"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="建档日期"
                prop="create_time"
              >
                <el-input disabled v-model="trainerForm.create_time" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">诊断疾病</el-divider>
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="病史"
                prop="medical_history"
                :rules="[
                  {
                    required: true,
                    message: '请输入',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input v-model="trainerForm.medical_history"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="诊断疾病"
                prop="disease"
                :rules="[
                  {
                    required: true,
                    message: '请选择',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select v-model="trainerForm.disease" multiple>
                  <el-option
                    v-for="item in diseaseList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">常规检查信息</el-divider>
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="检查项目"
                prop="check_items"
                :rules="[
                  {
                    required: true,
                    message: '请选择',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select v-model="trainerForm.check_items" multiple>
                  <el-option
                    v-for="item in checkItemsList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="检查情况"
                prop="check_result"
                :rules="[
                  {
                    required: true,
                    message: '请输入',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input v-model="trainerForm.check_result"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="责任医生"
                prop="charge_doctor"
                :rules="[
                  {
                    required: true,
                    message: '请选择',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select v-model="trainerForm.charge_doctor" filterable>
                  <el-option
                    v-for="item in doctorList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="主训医生"
                prop="train_doctor"
                :rules="[
                  {
                    required: true,
                    message: '请选择',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select v-model="trainerForm.train_doctor" filterable>
                  <el-option
                    v-for="item in doctorList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider content-position="left">历史报告记录图片</el-divider>
          <el-upload
            ref="uploadRef"
            v-model:file-list="fileList"
            :auto-upload="false"
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            list-type="picture-card"
            accept=".jpg, .jpeg, .png"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :on-change="handleChange"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form>
      </div>
      <div class="footer-dialog">
        <el-button v-if="title != '查看'" type="primary" @click="savePwd(formRef)">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="pages-trainer">
import { ref, reactive } from "vue";
import { FormOption, FormOptionList } from "@/types/form-option";
import { CirclePlusFilled, UploadFilled, Download, Plus } from "@element-plus/icons-vue";
import TableSearch from "@/components/table-search.vue";
import TableCustom from "@/components/table-custom.vue";
import TableEdit from "@/components/table-edit.vue";
import { Trainer } from "@/types/trainer";
import { ElMessage, FormInstance, ElMessageBox } from "element-plus";
import { DiseaseService } from "@/api/service/diseaseService";
import { CheckItemService } from "@/api/service/checkItemService";
import { DoctorService } from "@/api/service/doctorService";
import { TrainerService } from '@/api/service/trainerService';
import { saveAs } from 'file-saver'
import dayjs from 'dayjs'
import type { UploadProps, UploadUserFile, UploadFile } from 'element-plus'
import { uploadFile, getFileStream } from "@/api/index";

const query = reactive<Trainer>({
  name: null,
  age: null,
  tel: null,
  trainDoctor: null,
  chargeDoctor: null,
});

const searchParam = reactive({
  pageNum: 1,
  pageSize: 10,
  params: query
})

const searchOpt = ref<FormOptionList[]>([
  { type: "input", label: "姓名", prop: "name" },
  {
    type: "select",
    label: "性别",
    prop: "gender",
    opts: [
      { label: "男", value: 1 },
      { label: "女", value: 2 },
    ],
  },
  { type: "input", label: "联系电话", prop: "tel", format: "number" },
]);
const genderList = ref([
  { label: "男", value: 1 },
  { label: "女", value: 2 },
]);
const familyList = ref([
  { label: "三代同堂", value: 1 },
  { label: "核心家庭", value: 2 },
  { label: "单亲家庭", value: 2 },
]);

const fileList = ref<UploadUserFile[]>([
  // {
  //   name: 'food.jpeg',
  //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  // },
])
const formRef = ref<FormInstance>();
const rowData = ref({});
const isEdit = ref(false);
const title = ref('新增');
const visible = ref(false);
let trainerForm = ref({
  // basis
  name: null,
  gender: null,
  age: null,
  birthday: null,
  family_structure: null,
  contact: null,
  tel: null,
  address: null,
  // 诊断疾病
  medical_history: null,
  disease: null,
  //常规检查信息
  check_items: null,
  check_result: null,
  train_doctor: null,
  charge_doctor: null,
  create_time: dayjs(new Date().getTime()).format('YYYY-MM-DD'),
  trainer_files: [],
});
// 新增/编辑弹窗相关
let options = ref<FormOption>({
  labelWidth: "100px",
  span: 12,
  list: [
    { type: "input", label: "姓名", prop: "name", required: true },
    { type: "input", label: "性别", prop: "gender", required: true },
    { type: "input", label: "年龄", prop: "age", required: true },
    {
      type: "input",
      label: "contact",
      prop: "家长",
      required: true,
      hide: true,
    },
    {
      type: "input",
      label: "tel",
      prop: "联系电话",
      required: true,
      hide: true,
    },
  ],
});

const getData = async () => {
  const res = await TrainerService.page(searchParam);
  tableData.value = res.list || [];
  tableData.value.map(item =>{
    item.charge_doctor = Math.round(item.charge_doctor)
    item.family_structure = Math.round(item.family_structure)
    item.gender = Math.round(item.gender)
    item.train_doctor = Math.round(item.train_doctor)
  })
  page.total = res.total;
};
getData();
const savePwd = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) return false;
    let result = null;
    // const formData = new FormData()
    // if(fileList.value.length > 0){
    //   fileList.value.forEach(e => {
    //     formData.append('fileList', e.raw)
    //   })
    //   formData.append('form', trainerForm.value)
    // }
    console.log('trainerForm.value==',trainerForm.value)
    if(isEdit.value){
      result = await TrainerService.update(trainerForm.value)
      ElMessage.success("修改成功");
    } else {
      result = await TrainerService.create(trainerForm.value)
      ElMessage.success("新增成功");
    }
    visible.value = false;
    // formRef.value.resetFields();
    getData();
  });
};
const diseaseList = ref([]);
const getDiseaseList = async () => {
  const res = await DiseaseService.list();
  diseaseList.value = res;
};
getDiseaseList();

const checkItemsList = ref([]);
const getCheckItemsList = async () => {
  const res = await CheckItemService.list();
  checkItemsList.value = res;
};
getCheckItemsList();

const doctorList = ref([]);
const getDoctorList = async () => {
  const res = await DoctorService.list();
  doctorList.value = res;
};
getDoctorList();
const isPhoneNum = (rule, value, callback) => {
  const reSpaceCheck = /^1[3456789]\d{9}$/;
  if (reSpaceCheck.test(value)) {
    return callback();
  } else {
    callback(new Error("请输入正确手机号码"));
  }
};
const closeDialog = () => {
  visible.value = false;
  trainerForm = ref({
    // basis
    name: null,
    gender: null,
    age: null,
    birthday: null,
    family_structure: null,
    contact: null,
    tel: null,
    address: null,
    // 诊断疾病
    medical_history: null,
    disease: null,
    //常规检查信息
    check_items: null,
    check_result: null,
    train_doctor: null,
    charge_doctor: null,
    trainer_files: null,
    create_time: dayjs(new Date().getTime()).format('YYYY-MM-DD')
  });
  uploadRef.value.clearFiles()
};

const handleSearch = () => {
  getData();
};
const fieldFormatter = (value:any) => {
  for(let i=0;i < genderList.value.length; i++){
    if(genderList.value[i].value == value){
      return genderList.value[i].label
    }
  }
  return value
}
let columns = ref([
  { type: "index", label: "序号", width: 120, align: "center" },
  { prop: "name", label: "姓名" },
  { prop: "gender", label: "性别", formatter: fieldFormatter },
  { prop: "age", label: "年龄" },
  { prop: "contact", label: "家长" },
  { prop: "tel", label: "联系电话" },
  { prop: "operator", label: "操作", width: 420 },
]);
const page = reactive({
  index: 1,
  size: 10,
  total: 0,
});
const tableData = ref([]);
const handleAdd = () => {
  title.value = '新增'
  visible.value = true
};
const handleView = (row) => {
  title.value = '查看'
  trainerForm.value = { ...row }
  fileList.value = []
  if(trainerForm.value.trainer_files?.length > 0){
    trainerForm.value.trainer_files.forEach(async item => {
      const file = await getFileStream(item.file_path);
      const url = URL.createObjectURL(new Blob([file.buffer]))
      fileList.value.push({name: item.file_name, url })
    })
  }
  visible.value = true
};
const handleDelete = async (row) => {
  const res = await TrainerService.delete(row.id)
    ElMessage.success('删除成功');
    getData();
};
const handleEdit = (row) => {
  title.value = '编辑'
  isEdit.value = true;
  trainerForm.value = { ...row }
  trainerForm.value.check_items = JSON.parse(trainerForm.value.check_items)
  trainerForm.value.disease = JSON.parse(trainerForm.value.disease)
  trainerForm.value.charge_doctor = Math.round(trainerForm.value.charge_doctor)
  trainerForm.value.family_structure = Math.round(trainerForm.value.family_structure)
  trainerForm.value.gender = Math.round(trainerForm.value.gender)
  trainerForm.value.train_doctor = Math.round(trainerForm.value.train_doctor)
  fileList.value = []
  if(trainerForm.value.trainer_files?.length > 0){
    trainerForm.value.trainer_files.forEach(async (item,index) => {
       const file = await getFileStream(item.file_path);
       const url = URL.createObjectURL(new Blob([file.buffer]))
      fileList.value.push({name: item.file_name, url })
    })
  }
  visible.value = true
};
const changePage = (val: number) => {};


// Excel导入相关
const fileInput = ref<HTMLInputElement>();
const handleImportClick = () => {
  if (!fileInput.value) {
    fileInput.value = document.createElement('input');
    fileInput.value.type = 'file';
    fileInput.value.accept = '.xlsx,.xls';
    fileInput.value.onchange = async (e) => {
      const files = (e.target as HTMLInputElement).files;
      if (!files || files.length === 0) return;
      try {
        await ElMessageBox.confirm('确定要导入这些患者数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        const loadingInstance = ElMessage({
          message: '正在导入数据...',
          type: 'info',
          duration: 0,
          customClass: 'loading-message'
        });
        try {
          await TrainerService.importFromExcel(files[0]);
          ElMessage.success('导入成功');
          getData();
        } catch (error) {
          ElMessage.error(`导入失败: ${error.message}`);
        } finally {
          loadingInstance.close();
        }
      } catch {
        // 用户取消
      }
    };
  }
  fileInput.value.click();
};

const downloadTemplate = async() => {
  try {
    // 使用新的对话框方式下载模板
    const filePath = await TrainerService.downloadTemplateWithDialog();
    if (filePath) {
      ElMessage.success(`模板已保存到: ${filePath}`);
    }
  } catch (error) {
    console.error('下载模板失败:', error);
    if (error instanceof Error && error.message.includes('用户取消了保存')) {
      ElMessage.info('用户取消了保存');
    } else {
      ElMessage.error('下载模板失败');
    }
  }
};

// 上传图片
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const uploadRef = ref();
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log('handleRemove=',uploadFile, uploadFiles)
  if(trainerForm.value.trainer_files?.length > 0){
    for(let i = 0; i<trainerForm.value.trainer_files.length;i++) {
      if(uploadFile.name == trainerForm.value.trainer_files[i].file_name){
        trainerForm.value.trainer_files.splice(i,1);
      }
    }
    console.log('trainerForm.value.trainer_fil1111=',trainerForm.value.trainer_files)
  }
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const uploadedFile = ref<File | null>(null)
const handleChange: UploadProps['onChange'] = async (file: UploadFile, uploadFiles) => {
  uploadedFile.value = file.raw
  // 如果有新上传的文件，先上传文件
  if (uploadedFile.value) {
    try {
      const fileName = await uploadFile(uploadedFile.value);
      let trainerFiles = {
        trainer_id: null,
        file_name: fileName,
        file_path: fileName
      }
      trainerForm.value.trainer_files?.push(trainerFiles)
      console.log('handleChange==', trainerForm.value)
    } catch (error) {
      console.error('文件上传失败:', error);
      ElMessage.error('文件上传失败，请重试');
    }
  }
}


const beforeUpload = (file: File) => {
  // 解决方法：上传之前 before-upload 判断文件类型
  const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);

  const whiteList = ["jpeg", "jpg", "png"];

  if (whiteList.indexOf(fileSuffix) === -1) {
    ElMessage.error("上传文件只能是 jpeg、jpg、png格式");
    return false;
  }

  if (file.size / 1024 / 1024 > 50) {
    ElMessage.error("上传文件大小不能超过 50MB!");
    return false;
  }
  fileList.value.fileInfo.forEach((item) => {
    if (item.name == file.name) {
      ElMessage.error("上传文件的与列表中文件名重复，请修改后再上传!");
      return (file.name = "niew" + file.name);
      //   return false;
    } else {
      return true;
    }
  });
};

</script>
<style scoped>
.content-dialog {
  height: 600px;
  overflow: hidden;
  overflow-y: scroll;
}
.footer-dialog {
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.content-dialog :deep(.el-divider__text) {
  color: var(--active-color);
}
</style>
